package net.tycmc.cty.ctyms.timejob.iems.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.tycmc.functions.util.MapGetter;
import com.tycmc.functions.util.StringUtil;

import net.tycmc.cty.ctyms.timejob.common.ListUtil;
import net.tycmc.cty.ctyms.timejob.common.EquipVersionCommon;
import net.tycmc.cty.ctyms.timejob.iems.dao.ParamConSaveAsFileDAO;

public class ParamConSaveAsFileService {
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
	private ParamConSaveAsFileDAO paramFileDAO;	

	public ParamConSaveAsFileDAO getParamFileDAO() {
		return paramFileDAO;
	}

	public void setParamFileDAO(ParamConSaveAsFileDAO paramFileDAO) {
		this.paramFileDAO = paramFileDAO;
	}

	public void startStat() {
		String rootFile = this.getRootCSVFile();
		String[] time = this.paramFileDAO.getCSVFileJobWorkTime();
		//can 设备参数信息保存为csv文件
		if(this.saveFileOfCanVclsParameters(rootFile,time)){
			
		}else{
			
		}
		//pp 设备参数信息保存为csv文件
		if(this.saveFileOfPPVclsParameters(rootFile,time)){
			
		}else{
			
		}
		//jpp 设备参数信息保存为csv文件
		if(this.saveFileOfJPPVclsParameters(rootFile,time)){
			
		}else{
			
		}
		//更新下次操作时统计的时间
		this.paramFileDAO.updateCSVFileWorkTime(time[1]);
		this.deleteHistoryFile(rootFile);
	}
	/**
	 * 删除3个月前的文件
	 **/
	private void deleteHistoryFile(String rootFile) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Calendar ca = Calendar.getInstance();
		ca.add(Calendar.DAY_OF_YEAR, -91);
		File dir = new File(rootFile + sdf.format(ca.getTime()));
		if(dir.exists()&&dir.isDirectory()){
			File[] childs = dir.listFiles();
			for(File one:childs){
			  one.deleteOnExit();
			}
		}
		if(!dir.delete()){
			dir.delete();
		}
	}
	/**
	 * jpp 设备参数信息保存为csv文件
	 **/
	private boolean saveFileOfJPPVclsParameters(String rootFile,String[] time) {
		String jppSoftVers = EquipVersionCommon.getSoftVerByAgrType("Vcl_JPP");
		List<Map<String,Object>> vcls414 = this.paramFileDAO.getVclsOfSoft(jppSoftVers);
//		if(null!= vcls414 && !vcls414.isEmpty())
//		System.out.println("JPP 设备   "+vcls414.size());
		this.saveFileOfParameters(rootFile,time,vcls414,"uds");
		this.saveFileOfParameters(rootFile,time,vcls414,"pgn");
		return true;
	}
	/**
	 * pp 设备参数信息保存为csv文件
	 **/
	private boolean saveFileOfPPVclsParameters(String rootFile,String[] time) {
		String ppSoftVers = EquipVersionCommon.getSoftVerByAgrType("Vcl_PP");
		List<Map<String,Object>> vcls412 = this.paramFileDAO.getVclsOfSoft(ppSoftVers);
//		if(null!= vcls412 && !vcls412.isEmpty())
//		System.out.println("pp 设备   "+vcls412.size());
		return this.saveFileOfParameters(rootFile,time,vcls412,"uds");
		
	}
	/**
	 * can 设备参数信息保存为csv文件
	 **/
	private boolean saveFileOfCanVclsParameters(String rootFile, String[] time) {
		String canSoftVers = EquipVersionCommon.getSoftVerByAgrType("Vcl_J");
		List<Map<String,Object>> vcls403 = this.paramFileDAO.getVclsOfSoft(canSoftVers);
//		if(null!= vcls403 && !vcls403.isEmpty())
//		System.out.println("can 设备   "+vcls403.size());
		return this.saveFileOfParameters(rootFile, time, vcls403, "can");
	}
	/**
	 * 保存制定设备制定类型的参数值为csv文件
	 **/
	public boolean saveFileOfParameters(String rootFile, String[] time,List<Map<String, Object>> vclList,String type){
		Date start = null;
		Date end = null;
		try {
			start = this.sdf.parse(time[0]);
			end = this.sdf.parse(time[1]);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		Calendar ca = Calendar.getInstance();
		ca.setTime(start);
		String tablename = null;
		List<Map<String,Object>> oneVclParm = null;//参数内容信息
		
		List<Map<String, Object>> dictionary = this.paramFileDAO.queryDictionaryOfParameter(type);
		int dicMax = new ListUtil().getDataMaxVal(dictionary, "dicID");
		
		while(ca.getTime().getTime()<end.getTime()){
			if(type.toLowerCase().equals("can")){
				tablename = "'Msg_CAN_Content_"+this.sdf.format(ca.getTime()).replaceAll("-", "")+"','Msg_CAN_"+this.sdf.format(ca.getTime()).replaceAll("-", "")+"'";
			}else if(type.toLowerCase().equals("uds")){
				tablename = "'Msg_UDS_Content_"+this.sdf.format(ca.getTime()).replaceAll("-", "")+"','Msg_UDS_"+this.sdf.format(ca.getTime()).replaceAll("-", "")+"'";
			}else if(type.toLowerCase().equals("pgn")){
				tablename = "'Msg_PGN_Content_"+this.sdf.format(ca.getTime()).replaceAll("-", "")+"','Msg_PGN_"+this.sdf.format(ca.getTime()).replaceAll("-", "")+"'";
			}	
			if(this.paramFileDAO.checkParameterTable(tablename)){
				
				if(null!=vclList && vclList.size()>0){
					for(Map<String,Object> oneVcl:vclList){
						/*if(MapGetter.getString(oneVcl, "VehicleID").equals("116099")){
							System.out.println("sssssssssssssss");
						}*/
						/*查询获取当天设备返回的参数信息*/
						oneVclParm = this.queryParameters(MapGetter.getString(oneVcl, "VehicleID"),this.sdf.format(ca.getTime()).replaceAll("-", ""),type);
						
						this.saveAsCSVFile(type,this.sdf.format(ca.getTime()).replaceAll("-", ""),rootFile,oneVcl,oneVclParm,dicMax);
					}
				}
			}
			ca.add(Calendar.DAY_OF_YEAR, 1);
		}
		return true;
	}
	/**
	 * 保存为csv文件
	 * @变更历史  jiyongtian 20140923 调整csv文件内容值
	 **/
	private void saveAsCSVFile(String type,String time,String rootFile,Map<String, Object> vcl,List<Map<String, Object>> paramValue,
			int maxDic){
		String VehicleNumber = MapGetter.getString(vcl,"VehicleNumber");
		String VehicleID = MapGetter.getString(vcl,"VehicleID");
		String flag = System.getProperty("line.separator");
		String splitFlag = "@#";
		StringBuffer strBuf = new StringBuffer();
		for(Map<String,Object> one:paramValue){
			one.remove("Msg_ID");
			//前10个位置保留参数的主信息，目前有设备ID、设备号、生成时间、接收时间、参数类型 五个，剩余五个预留  
//			strBuf.append(VehicleNumber+","+one.remove("MsgTime")+","+one.remove("SysTI_Name"));
			strBuf.append(VehicleID+splitFlag+VehicleNumber+splitFlag+one.remove("MsgTime")+splitFlag+one.remove("RcvTime")+splitFlag+one.remove("SysTI_Name"));
			for(int j=0;j<5;j++){
				strBuf.append(splitFlag);
			}
			
			for(int i=0;i<maxDic;i++){
				strBuf.append(splitFlag+MapGetter.getString(one, String.valueOf(i+1)));
			}
//			strBuf.append(","+one.remove("RcvTime"));
			strBuf.append(flag);
		}
		if(strBuf.toString().length()>0){
//			String fileName = this.createCSVFile(rootFile,VehicleNumber,time,type);
			String fileName = this.createCSVFile(rootFile,VehicleID,time,type);
			try {
				OutputStreamWriter os =  new OutputStreamWriter(new FileOutputStream(new File(fileName)), "GBK");
				os.write(strBuf.toString());
				os.flush();
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		} 
	}
	/**创建csv文件
	 * @param String rootFile 根目录 ：D:\\csv\\
	 * @param String VehicleFlag 设备标志：目前是设备ID的值
	 * @param String time 参数信息的生成日期
	 * @param String type 参数类型，can、uds、pgn 三种取值
	 * @更新历史  jiyongtian 20140923 
	 **/
	private String createCSVFile(String rootFile, String VehicleFlag,
			String time, String type) {
		File temp = new File(rootFile + time);
		if(!temp.exists()){
			temp.mkdir();
		}
		String fileName = rootFile + time+File.separator+VehicleFlag+"_"+time+"_"+type+".csv";
		File csv = new File(fileName);
		if(!csv.exists()){
			try {
				csv.createNewFile();
			} catch (IOException e) {
				temp.setWritable(true);
				try {
					csv.createNewFile();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
		}
		return fileName;
	}

	/**
	 * 获取参数信息
	 **/
	private List<Map<String, Object>> queryParameters(String vclID, String time, String type) {
		List<Map<String,Object>> main = null;
		List<Map<String,Object>> content = null;
		//查询主表信息
		main = this.paramFileDAO.queryMainTableMsg(vclID, time, type);
		//查询从表信息
		content = this.paramFileDAO.queryContentTableMsg(vclID,time,type);
		Map<String,List<Map<String,Object>>> contentMap = new ListUtil().groupBy("Msg_ID", content);
		content = null;
		if(main!=null){
			List<Map<String,Object>> tempContent = null;
			for(Map<String,Object> oneMain:main){
				tempContent = contentMap.get(oneMain.get("Msg_ID").toString());
				if(tempContent!=null && tempContent.size()>0){
					for(Map<String,Object> oneCon:tempContent){
						oneMain.put(MapGetter.getString(oneCon, "dicID"), MapGetter.getString(oneCon, "paramValue"));
					}
				}
			}
		}
		return main;
	}
	/**
	 * 获取保存路径的根目录
	 **/
	private String getRootCSVFile() {
		String reStr = "";
		Map<String,Object> rootMsg = this.paramFileDAO.getRootSaveFile();
		String localIP = "";
		try {
			localIP = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			
		} 
		String rootIP = MapGetter.getString(rootMsg, "Sys_Url_IP");
		String rootPath = MapGetter.getString(rootMsg, "Sys_Url_Repath");
		if((rootPath.lastIndexOf(File.separator)>=0)&&(rootPath.lastIndexOf(File.separator)!= rootPath.length())){
			rootPath += File.separator; 
		}
		if(StringUtil.isValid(localIP)){
			if(rootIP.equals(localIP)){
				reStr = rootPath;
			}else{
				reStr = rootIP + rootPath.substring(rootPath.lastIndexOf(":")+1);
			}
		}else{
			reStr = rootIP + rootPath.substring(rootPath.lastIndexOf(":")+1);
		}
		File root = new File(rootPath);
		if(!root.exists()){
			root.mkdirs();
			System.out.println("*****CSV文件根目录创建成功********");
		}else{
			System.out.println("*****CSV文件根目录创建失败********"+rootPath);
		}
//		return reStr;
		return rootPath;
	}
}